import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Service } from 'app/server/server';
import { Res } from 'app/public/model/Res.class';

@Injectable()
export class CudTableService {

  constructor(
    private http: Http, 
    private srv: Service
  ) { }

  /**
   * GET请求
   * @param url 
   */ 
  getRequest(url) {
    return this.http
               .get(url)
               .toPromise()
               .then(res => res.json())
               .catch(err => { 
                  return err;
               });
  }

  /**
   * POST请求
   * @param url 
   * @param data 
   * @param option 
   */ 
  postRequest(url: string, data: any, option?: any) {
    return this.http
               .post(url, data)
               .toPromise()
               .then(res => res.json())
               .catch(err => {
                 return err;
               })
  }

  public prompt(res: Res): boolean {
    if (res.result_code === '0000') {
      this.srv.prompt = { prompt: true, success: true, fail: false, promptStatement: res.message }
      this.srv.promptclose;
      return true
    } else {
      this.srv.prompt = { prompt: true, success: false, fail: true, promptStatement: res.message }
      this.srv.promptclose;
      return false
    }
  }
  public download(url) {
    let a = document.createElement('a');
    a.target = '_blank';
    a.href = url;
    a.download = 'exportInvoices';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
}
